package com.glory.hikvisionmobile.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.from.ChangeShiftsBean;
import com.glory.hikvisionmobile.bean.from.LocationBean;
import com.glory.hikvisionmobile.bean.from.LocationListBean;
import com.glory.hikvisionmobile.bean.from.UserBean;
import com.glory.hikvisionmobile.bean.from.UserListBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * FileName: From_ChangeShiftsActivity
 * Author: XJH
 * Date: 2020/2/3 17:13
 * Description: 交接班记录表单
 * History:
 */
public class From_ChangeShiftsActivity extends BaseActivity {
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.tvRegion)
    TextView tvRegion;
    @BindView(R.id.ivRegionListArrow)
    ImageView ivRegionListArrow;
    @BindView(R.id.flRegionList)
    FrameLayout flRegionList;
    @BindView(R.id.tvClasses)
    TextView tvClasses;
    @BindView(R.id.ivClassesListArrow)
    ImageView ivClassesListArrow;
    @BindView(R.id.flClassesList)
    FrameLayout flClassesList;
    @BindView(R.id.tvUser)
    TextView tvUser;
    @BindView(R.id.etMatter)
    FreeUI_ClearEditText etMatter;
    @BindView(R.id.tvReplay)
    TextView tvReplay;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvChangeUser)
    TextView tvChangeUser;
    @BindView(R.id.ivChangeUserListArrow)
    ImageView ivChangeUserListArrow;
    @BindView(R.id.flChangeUserList)
    FrameLayout flChangeUserList;
    @BindView(R.id.llCheckUserLayout)
    LinearLayout llCheckUserLayout;
    @BindView(R.id.tvChangeUsers)
    TextView tvChangeUsers;
    @BindView(R.id.llChangeUserLayout)
    LinearLayout llChangeUserLayout;
    private ChangeShiftsBean changeShiftsBean;
    private String classes;
    private List<String> classesList = new ArrayList<>();
    private FreeUI_GeneralPop classPop;
    private List<String> locationList = new ArrayList<>();
    private List<UserBean> userList = new ArrayList<>();
    private FreeUI_GeneralPop locationPop;
    private FreeUI_GeneralPop userPop;
    private String location;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_from_change_shifts;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        changeShiftsBean = (ChangeShiftsBean) bundle.getSerializable("ChangeShiftsBean");
        if (changeShiftsBean != null) {
            tvReplay.setVisibility(View.GONE);
            tvTime.setText(changeShiftsBean.getCreated());
            tvRegion.setText(changeShiftsBean.getArea());
            flRegionList.setEnabled(false);
            tvClasses.setText(changeShiftsBean.getShift());
            flClassesList.setEnabled(false);
            tvUser.setText(changeShiftsBean.getHandoverPer());
            tvChangeUsers.setText(changeShiftsBean.getHandover());
            llChangeUserLayout.setVisibility(View.VISIBLE);
            llCheckUserLayout.setVisibility(View.GONE);
            etMatter.setText(changeShiftsBean.getItem());
            etMatter.setEnabled(false);
        } else {
            try {
                tvTime.setText(FreeApi_DateUtils.longToString(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            tvUser.setText(Constant.CURRENT_USER);
        }

    }

    @Override
    protected void initData() {
        NetUtils.getSelectorList("JJBShifts", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                classesList = list;
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });

        NetUtils.requestDara("HIK.PdaBaseLocation", this, null, new FreeUI_DialogEntityCallBack<BaseResponseBean<LocationListBean>>
                (new TypeToken<BaseResponseBean<LocationListBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LocationListBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    locationList.clear();
                    List<LocationBean> locationBeans = response.body().getBody().getxPdaLocations();
                    for (LocationBean bean : locationBeans) {
                        locationList.add(bean.getName() + "/" + bean.getDescription());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LocationListBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaBaseLocation");
            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("交接班记录表");
        freeUI_titleView.setRightListener("取消", v -> {
            if (changeShiftsBean != null) {
                return;
            }

            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    tvClasses.setText("");
                    tvRegion.setText("");
                    etMatter.setText("");
                    tvChangeUser.setText("");
                    classes = "";
                    location = "";
                    initData();
                }
            });


        });
        return new FreeUI_AddViewEntity("header", llMain);
    }


    @OnClick({R.id.flRegionList, R.id.flClassesList, R.id.flChangeUserList, R.id.tvReplay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flRegionList:
                if (locationList.size() <= 0) {
                    showToast("未获取到区域列表", false);
                    return;
                }

                if (locationPop != null) {
                    if (locationPop.isShowing()) {
                        locationPop.dismiss();
                    }
                } else {
                    locationPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flRegionList.getWidth(), locationList, ivRegionListArrow, (code, i) -> {
                        tvRegion.setText(code);
                        location = code.split("/")[0];
                        //根据区域查用户
                        tvChangeUser.setText("");
                        userPop = null;
                        JsonObject map = new JsonObject();
                        map.addProperty("phone2", location);
                        map.addProperty("department", "");
                        NetUtils.requestDara("HIK.PdaADUserQuery", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<UserListBean>>
                                (new TypeToken<BaseResponseBean<UserListBean>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<UserListBean>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                                    userList = response.body().getBody().getxPdaADUsers();
                                } else {
                                    userList.clear();
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<UserListBean>> response) {
                                super.onError(response);
                                loadError(response.getException(), "HIK.PdaADUserQuery");
                            }
                        });
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivRegionListArrow);
                locationPop.showAsDropDown(flRegionList, 0, 0);
                break;
            case R.id.flChangeUserList:
                if (userList.size() <= 0) {
                    showToast("未获取到被交接人列表", false);
                    return;
                }

                if (userPop != null) {
                    if (userPop.isShowing()) {
                        userPop.dismiss();
                    }
                } else {
                    userPop = DialogUtils.getManyChoosePop(userList, getApplicationContext(), flChangeUserList.getWidth(), ivChangeUserListArrow, new DialogUtils.popCallback() {
                        @Override
                        public void onSuccess(List<String> list) {
                            if (list.size() > 0) {
                                StringBuffer sb = new StringBuffer();
                                for (String str : list) {
                                    sb.append(str + ",");
                                }
                                tvChangeUser.setText(sb.toString());
                            } else {
                                tvChangeUser.setText("");
                            }
                        }
                    });
                }
                DialogUtils.setArrowShow(ivChangeUserListArrow);
                userPop.showAsDropDown(flChangeUserList, 0, 0);
                break;
            case R.id.flClassesList:
                if (classesList.size() <= 0) {
                    showToast("未获取到班次列表", false);
                }

                if (classPop != null) {
                    if (classPop.isShowing()) {
                        classPop.dismiss();
                    }
                } else {
                    classPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flClassesList.getWidth(), classesList, ivClassesListArrow, (code, i) -> {
                        tvClasses.setText(code);
                        classes = code.split("/")[0];
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivClassesListArrow);
                classPop.showAsDropDown(flClassesList, 0, 0);
                break;
            case R.id.tvReplay:

                initPermission("Submit", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        submit();
                    }
                });

                break;
        }
    }

    private void submit() {
        String matter = etMatter.getText().toString().trim();
        String changeUser = tvChangeUser.getText().toString().trim();
        if (FreeApi_StringUtils.isEmpty(changeUser)) {
            showToast("被交接人不能为空", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(classes)) {
            showToast("班次不能为空", false);
            return;
        }

        if (FreeApi_StringUtils.isEmpty(matter)) {
            showToast("事项不能为空", false);
            etMatter.setText("");
            etMatter.requestFocus();
            return;
        }

        if (FreeApi_StringUtils.isEmpty(location)) {
            showToast("区域不能为空", false);
            return;
        }

        DialogUtils.showLoginDialog(this, Constant.CURRENT_USER, new DialogUtils.signCallback() {
            @Override
            public void onSignSuccess() {
                JsonObject map = new JsonObject();
                ChangeShiftsBean bean = new ChangeShiftsBean(location, classes, tvUser.getText().toString().trim(), changeUser, matter);
                map.addProperty("actionType", "save");
                map.addProperty("formType", "JJB");
                map.add("xPdaFormJiaoJieBan", new JsonParser().parse(new Gson().toJson(bean)).getAsJsonObject());
                NetUtils.requestDara("HIK.PdaForm", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>
                        (new TypeToken<BaseResponseBean<?>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<?>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            showConfirmDialog(From_ChangeShiftsActivity.this, "提交成功");
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<?>> response) {
                        super.onError(response);
                        loadError(response.getException(), "HIK.PdaForm");
                    }
                });
            }
        }, getSupportFragmentManager());


    }
}
